import { PROJECTINFO, TOKEN, USERINFO,APPID } from '@/utils/const'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {sessionStorage,localStorage as localStorage1} from "@/utils/storage"
import { loginApi } from '@/api/login/api'
import store from "@/store"
import { objectType } from '@/types/system-types'
////   此模块作为登录、权限模块管理
export const loginStore = defineStore('login', () => { 
    const token = ref<string>(sessionStorage.get(TOKEN) || "")
    const projectInfo=localStorage1.get(PROJECTINFO)
    const appId=localStorage1.get(APPID)


    const login = (userInfo: { username: string, password: string }, isRememberPwd: boolean) => {
        
        return new Promise((resolve, reject) => {
            console.log('suerinfor',userInfo)
            loginApi(userInfo).then(res => {
                console.log('loin-reback', res)
                const {code}=res as unknown as {code:string,data:any,msg:string}
                if (code === '20006') {
                    resolve(res)
                    return
                }
                const { data } = res
                console.log('===loginapi', data)
                sessionStorage.set(TOKEN, 'Bearer '+data.access_token)
                // sessionStorage.set(TOKEN, data.access_token || data.token )
                sessionStorage.set(USERINFO, data)
                if (isRememberPwd) {
                    localStorage.setItem("username", userInfo.username);
                    localStorage.setItem("password", userInfo.password);
                } else {
                    localStorage.setItem("username", '');
                    localStorage.setItem("password", '');
                  }
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    }


    const setProInfo = (projectInfo: objectType) => {
        localStorage1.set(PROJECTINFO,projectInfo)
    }
    const setAppInfo = (id: string) => {
        localStorage1.set(APPID,id)
    }


return {token,login,projectInfo,setProInfo,setAppInfo,appId}

})

export function userStoreHook() {
    return loginStore(store)
}


